<script setup>
import {computed, onMounted, ref} from "vue";
import SingleLineInput from "../../components/preview/SingleLineInput.vue";
import EidtSingleLineInput from "../../components/workbench/EidtSingleLineInput.vue";
import EditRadioInput from "../../components/workbench/EditRadioInput.vue";
import {
    getCheckboxData,
    getLineInput,
    getRadioData,
    getRateData,
    getTextarea,
    getTimePickerData
} from "../../utils/InitData.js";
import RadioInput from "../../components/preview/RadioInput.vue";
import QuestionConfig from "./QuestionConfig.vue";
import {router} from "../../router/index.js";
import {getSurveysApi, saveSurveysApi} from "../../apis/SurveysApi.js";
import {Notification, Modal, Message} from "@arco-design/web-vue";
import {useRoute} from "vue-router";
import EidtSingleTextarea from "../../components/workbench/EidtSingleTextarea.vue";
import SingleTextarea from "../../components/preview/SingleTextarea.vue";
import {DEV_SURVEYS_KEY, IS_PREVIEW_DEV_KEY} from "../../config/index.js";
import PreviewDev from "../preview/PreviewDev.vue";
import EditCheckboxInput from "../../components/workbench/EditCheckboxInput.vue";
import CheckboxInput from "../../components/preview/CheckboxInput.vue";
import {dayjs} from "@arco-design/web-vue/es/_utils/date.js";
import useStore from "../../store/index.js";
import EidtSingleRate from "../../components/workbench/EidtSingleRate.vue";
import SingleRate from "../../components/preview/SingleRate.vue";
import SingleTimePicker from "../../components/preview/SingleTimePicker.vue";
import EidtTimePicker from "../../components/workbench/EidtTimePicker.vue";
import {quickList} from "../../utils/QuickQuestionUtil.js";
const defaultBg = new URL('../../assets/default-bg.png', import.meta.url).href;

const route = useRoute()
const surveys = ref({
    title: '新建问卷',
    description:'',
    bgimg:'',
    questions:[],
    type:0
})
const store = useStore()
const surveysStyle = ref({
    // backgroundImage: surveys.value.bgimg ? "url(" + surveys.value.bgimg + ")": `url(${defaultBg})`,
})
const isCreateTemplate = ref(false)
const isSaveLoading = ref(false)
const currentFourIndex = ref(0);
const saveQuestion = async () => {
    Modal.warning({
        title: '提示',
        content: '确认保存吗？',
        onOk: async () => {
            isSaveLoading.value = true
            if (isCreateTemplate.value){
                surveys.value.isTemplate = 1
            }
            //多选题去掉题目中的value属性
            surveys.value.questions.forEach(item => {
                if (item.type === 1){
                    delete item.value
                }
            })
            //保存到数据库中
            const res = await saveSurveysApi(surveys.value)
            isSaveLoading.value = false
            if(res.code === 0){
                Notification.success("保存成功")
                router.replace("/workbench/" + res.data.id)
                //刷新页面
                setTimeout(() => {
                    location.reload()
                }, 250);
            }else{
                Notification.error(res.message)
            }
        }
    })
}
const addRadio = () => {
    let data = getRadioData()
    data.orders = surveys.value.questions.length + 1;
    surveys.value.questions.push(data)
}
const addCheckbox = () => {
    let data = getCheckboxData()
    data.orders = surveys.value.questions.length + 1;
    surveys.value.questions.push(data)
}
const addRate = () => {
    let data = getRateData()
    data.orders = surveys.value.questions.length + 1;
    surveys.value.questions.push(data)
}
const addTimePicker = () => {
    let data = getTimePickerData()
    data.orders = surveys.value.questions.length + 1;
    surveys.value.questions.push(data)
}

const addLineInputDom = () => {
    let data = getLineInput()
    data.orders = surveys.value.questions.length + 1;
    surveys.value.questions.push(data)
}
const addTextareaDom = () => {
    let data = getTextarea()
    data.orders = surveys.value.questions.length + 1;
    surveys.value.questions.push(data)
}
const logTest = () => {
    console.log(surveys.value)
}
const fourEvent = (index) => {
    currentFourIndex.value = index;
}

// 重新编制序号
const refreshOrders = () => {
    surveys.value.questions.forEach((item,index) => {
        item.orders = index + 1
    })
}
const delQuestion = (index) => {
    surveys.value.questions.splice(currentFourIndex.value,1)
    //刷新序号
    refreshOrders()
}

const goPreView = () => {
    //先将当前数据 保存到 sessionStorage
    sessionStorage.setItem(DEV_SURVEYS_KEY,JSON.stringify(surveys.value))
    sessionStorage.setItem(IS_PREVIEW_DEV_KEY,'true')
    //跳转到专门的preview-dev路由 再从localStorage中获取数据进行预览
    router.push("/preview-dev")
}

//计算属性 所有题目的 orders列表
const orderList = computed(() => {
    return surveys.value.questions.map(item => item.orders)
})

//交换题目顺序
const orderSelectChange  = (newOrder,oldOrder) => {
    console.log('addad',newOrder,oldOrder)
    let oldIndex = surveys.value.questions.findIndex(item => item.orders === oldOrder)
    let newIndex = surveys.value.questions.findIndex(item => item.orders === newOrder)
    if(oldIndex >= 0 && newIndex >= 0){
        surveys.value.questions[oldIndex].orders = newOrder
        surveys.value.questions[newIndex].orders = oldOrder

        let temp = surveys.value.questions[oldIndex]
        surveys.value.questions[oldIndex] = surveys.value.questions[newIndex]
        surveys.value.questions[newIndex] = temp

    }

}
/**
 * 快捷添加
 */
const addQuick = (item) => {
    item.callFun(surveys.value.questions)
}

onMounted(async () => {

    if (route.params.id){
        const res = await getSurveysApi(route.params.id)
        if(res.code === 0){
            surveys.value = res.data
        }else{
            Notification.error(res.message)
        }
    }
    //如果从预览界面返回
    let isDev = sessionStorage.getItem(IS_PREVIEW_DEV_KEY);
    let json = sessionStorage.getItem(DEV_SURVEYS_KEY)
    if(isDev === 'true' && json){
        let obj= JSON.parse(json)
        surveys.value = obj
        sessionStorage.removeItem(DEV_SURVEYS_KEY)
        sessionStorage.removeItem(IS_PREVIEW_DEV_KEY)
    }

    //是否为创建模板
    if (route.query.t === '1'){
        //检查登录用户是否为管理员
        if (store.userIsLogin && store.userinfo.userRole === 'admin'){
            isCreateTemplate.value = true
            surveys.value.title = '新建模板'
        }else{
            await Message.error('权限不足，无法创建问卷模板')
            router.back()
        }
    }

})
</script>

<template>
<div class="maxDiv w-full px-8 py-12 min-h-full flex justify-around " :style="surveysStyle">
    <!--    问卷设计工具-->
    <a-affix>
        <div class="w-64 min-h-96 rounded border-2 py-4 px-2 bg-white shadow-lg ">
            <p class="text-center text-md">设计工具</p>
            <a-divider />
            <div @click="addLineInputDom" class="mx-auto text-center mb-1 cursor-pointer hover:bg-blue-400 rounded py-1"><icon-pen-fill />单行输入</div>
            <div @click="addTextareaDom" class="mx-auto text-center mb-1 cursor-pointer hover:bg-blue-400 rounded py-1"><icon-menu />多行输入</div>
            <div @click="addRadio" class="mx-auto text-center mb-1 cursor-pointer hover:bg-blue-400 rounded py-1"><icon-check-circle />单选题目</div>
            <div @click="addCheckbox" class="mx-auto text-center mb-1 cursor-pointer hover:bg-blue-400 rounded py-1"><icon-check-square />多选题目</div>
            <div @click="addRate" class="mx-auto text-center mb-1 cursor-pointer hover:bg-blue-400 rounded py-1"><icon-star />评分</div>
            <div @click="addTimePicker" class="mx-auto text-center mb-1 cursor-pointer hover:bg-blue-400 rounded py-1"><icon-calendar-clock />时间选择器</div>
            <a-divider />
            <p class="text-center text-md">快捷添加</p>
            <a-divider />
            <div>
                <div @click="addQuick(quick)"
                     v-for="quick in quickList"
                     class="mx-auto text-center mb-1 cursor-pointer hover:bg-blue-400 rounded py-1">
                    {{ quick.name }}
                </div>
            </div>
        </div>
    </a-affix>

<!--    问卷预览界面-->
    <div  class="max-w-3xl mx-auto rounded border-2 bg-white shadow-lg px-7 pb-10 flex-grow">
        <h1 class="text-2xl text-center font-bold my-4">{{surveys.title}}</h1>
        <a-input placeholder="问卷标题" size="large" allow-clear v-model="surveys.title"/>

        <a-input class="mt-4" placeholder="问卷描述" size="large" allow-clear v-model="surveys.description"/>

<!--        每题问题-->
        <div v-for="(question,index) in surveys.questions" class="mt-5" :key="question.orders">
            <div class="border-b pb-3 mb-3" v-if="question.type === 2">
                <EidtSingleLineInput  :data="question" v-show="currentFourIndex === index" @click="fourEvent(index)"/>
                <SingleLineInput style="z-index: 10" :data="question" v-show="currentFourIndex !== index" @click="fourEvent(index)"/>
            </div>

            <div class="border-b pb-3 mb-3" v-if="question.type === 3">
                <EidtSingleTextarea  :data="question" v-show="currentFourIndex === index" @click="fourEvent(index)"/>
                <SingleTextarea  :data="question" v-show="currentFourIndex !== index" @click="fourEvent(index)"/>
            </div>

            <div class="border-b pb-3 mb-3" v-if="question.type === 1">
                <EditCheckboxInput  :data="question" v-show="currentFourIndex === index" @click="fourEvent(index)"/>
                <CheckboxInput  :data="question" v-show="currentFourIndex !== index" @click="fourEvent(index)"/>
            </div>

            <div class="border-b pb-3 mb-3" v-if="question.type === 0">
                <EditRadioInput  :data="question" v-show="currentFourIndex === index" @click="fourEvent(index)"/>
                <RadioInput :data="question" v-show="currentFourIndex !== index" @click="fourEvent(index)"/>
            </div>

            <div class="border-b pb-3 mb-3" v-if="question.type === 4">
                <EidtSingleRate  :data="question" v-show="currentFourIndex === index" @click="fourEvent(index)"/>
                <SingleRate :data="question" v-show="currentFourIndex !== index" @click="fourEvent(index)"/>
            </div>
            <div class="border-b pb-3 mb-3" v-if="question.type === 5">
                <EidtTimePicker  :data="question" v-show="currentFourIndex === index" @click="fourEvent(index)"/>
                <SingleTimePicker :data="question" v-show="currentFourIndex !== index" @click="fourEvent(index)"/>
            </div>


        </div>

        <div v-if="surveys.questions.length === 0">
            <a-result status="404" subtitle="暂无问题，快去添加问题吧！">
            </a-result>
        </div>

        <div class="w-full flex justify-center mt-6">
            <a-button class="w-52" :loading="isSaveLoading" status="success" type="primary" @click="saveQuestion">保存</a-button>
<!--            <a-button class="w-52 ml-5" type="primary" @click="logTest">打印表单</a-button>-->
            <a-button class="w-52 ml-5" type="primary" @click="goPreView">预览表单</a-button>

        </div>
    </div>

<!--    每题配置-->
    <a-affix>
        <div class="w-64 max-h-fit rounded border-2 pt-4 pb-10 px-2 bg-white shadow-lg ">
            <p class="text-center text-md">题目配置</p>
            <a-divider />
            <QuestionConfig :order-list="orderList"
                            :change-order="orderSelectChange"
                            v-model="surveys.questions[currentFourIndex]" :del-question="delQuestion"/>
        </div>
    </a-affix>

</div>
</template>

<style scoped>
.maxDiv{

}
</style>
